When using null-related annotations at global scope level, for instance using javax.annotation.ParametersAreNonnullByDefault
(from
JSR-305) at package level, it means that all the parameters to all the methods included in the package will, or should, be considered
Non-null
. It is equivalent to annotating every parameter in every method with non-null annotations (such as @Nonnull
).
The rule raises an issue every time a parameter could be null
for a method invocation, where the method is annotated as forbidding
null parameters.
Noncompliant code example
@javax.annotation.ParametersAreNonnullByDefault
class A {
void foo() {
bar(getValue()); // Noncompliant - method 'bar' do not expect 'null' values as parameter
}
void bar(Object o) { // 'o' is by contract expected never to be null
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
Compliant solution
Two solutions are possible:
- The signature of the method is correct, and null check should be done prior to the call.
- The signature of the method is not coherent and should be annotated to allow null values being passed as parameter
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
Object o = getValue();
if (o != null) {
bar(o); // Compliant - 'o' can not be null
}
}
void bar(Object o) {
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
or
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
bar(getValue());
}
void bar(@javax.annotation.Nullable Object o) { // annotation was missing
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}